package com.jzone.teacherajax.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jzone.teacherajax.pojo.Teacher;
import com.jzone.teacherajax.pojo.Result;
import com.jzone.teacherajax.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@CrossOrigin(origins = {"*", "null"})
@RestController
@RequestMapping("/teacher")
public class TeacherController {

    @Autowired
    private TeacherService teacherService;

    @PostMapping("/add")
    public Result<Teacher> add(@RequestBody @Validated Teacher teacher) {
        teacherService.add(teacher);
        return Result.success(teacher);
    }

    @PutMapping("/update")
    public Result<Teacher> update(@RequestBody @Validated Teacher teacher) {
        System.out.println("Received Teacher: " + teacher); // 打印收到的对象
        teacherService.update(teacher);
        return Result.success(teacher);
    }

    @DeleteMapping("/delete/{id}")
    public Result<Void> delete(@PathVariable Integer id) {
        teacherService.delete(id);
        return Result.success();
    }

    @GetMapping("/teachers")
    public Result<PageInfo<Teacher>> getAllTeachers(@RequestParam(defaultValue = "1") int page,
                                                    @RequestParam(defaultValue = "20") int size) {
        System.out.println("Received page: " + page + ", size: " + size);
        PageHelper.startPage(page, size);  // 设置分页
        List<Teacher> teachers = teacherService.getAllTeachers(page, size); // 调用服务方法
        PageInfo<Teacher> pageInfo = new PageInfo<>(teachers);
        System.out.println("PageInfo: " + pageInfo);
        return Result.success(pageInfo);
    }


    @GetMapping("/teachers/employeeId/{employeeId}")
    public Result<Teacher> getTeacherByEmployeeId(@PathVariable Integer employeeId) {
        Teacher teacher = teacherService.getTeacherByEmployeeId(employeeId);
        if (teacher == null) {
            return Result.error("教师信息未找到");
        }
        return Result.success(teacher);
    }

    @GetMapping("/teachers/count")
    public Result<Integer> getTeacherCount() {
        int count = teacherService.getTeacherCount();
        return Result.success(count);
    }
}
